<?php
/*
 * Author :basanas
 */
require_once ('include/css_head.php');
require_once ('include/functions.php');
require_once ('include/header.php');

require_once ('../bl/bl.php');
require_once ('../Frameworks/Objects/entity.php');
require_once ('../Frameworks/Objects/attribute.php');

if ( !empty($_POST['entity_ids']) ) {
    $nEntities = count(split(",",$_POST['entity_ids']));
}
else
    $nEntities = 0;

if ( ( isset($_POST['id']) && !is_null($_POST['id']) ) && !empty($_POST['entity_ids']) && ($nEntities > 1) && !empty($_POST['weights']) )
{
        $id = $_POST['id'];
        $cat = BL_getCategory($id);

        $entityIDs = explode(",",$_POST['entity_ids'] );
        $weightList = explode(",", $_POST['weights']);
        $numEntities = count($entityIDs);

        // Pairnoume ta dedomena tou ranking
        $rankArray = BL_getRanking($entityIDs, $weightList, 0);

        // Kratame kai th lista twn attributes ka8ws kai to plh8os tous
        $attributes = BL_getAttributes($entityIDs);
        $numAttributes = count($attributes[0]);

        // Kanonikopoioume ta scores gia na einai amesh h dhmiourgia twn progress bars
        $normScores = normalizeScores($rankArray[1]);

        // Pairnoume kai tis entities gia na exoume th plhroforia tou onomatos
        $entities = BL_getEntities($entityIDs);
}
else if ( !isset($_POST['id']) ) {
    UI_registerError('msg_warning', "You must first browse a category and select some entities to compare!");
    header("location: index.php");
    exit(0);
}
else if( !isset($_POST['weights']) )
{
    UI_registerError('msg_warning', "You must first input your preferences!");
    UI_registerError('msg_info', "First select some entities, and then give a weight to the attributes according to your interests");
    header("location: browse.php?id=".$_GET['id']);
    exit(0);
}
else
{
    UI_registerError('msg_error', "An error has occured. Please repeat the procedure.");
    header("location: index.php");
    exit(0);
}
?>

<div id="visRanking" style="margin: 0 3% 0 3%">
    <!-- TODO: onClick na kaleitai allh rendering function -->
        <span style="display: block; padding: 5px; margin: 0 25% 0 25%" class="blockHeader" id="catLink">Category:
            <a href="browse.php?id=<?php echo $id?>"><?php echo $cat->GetName()?> (Browse category)</a></span>

        <div style="width: 50%; margin: 0px auto 20px auto;">
            Visualization:
            <input type="radio" name="value" checked="checked" value="measurable" /> Total score
            <!--|
            <input type="radio" name="value" value="measurable" /> Per Attribute |
            <input type="radio" name="value" value="measurable" /> Lorem Ipsum
            -->
        </div>

<!------------------------------>
<!-- Data visualization table -->
<!------------------------------>

    <div id="visGraph">
        <table id="visGraphTable" class="tablesorter blockGrey">
            <thead>
            <tr>
                <th class="tC tCC">Entities</th>
                <th class="tC tCC">Scores</th>
            </tr>
            </thead>
            <tbody>
            <?php
            $i=0;
            foreach ($rankArray[1] as $key => $entity)
            {
            ?>
            <tr>
                <td class="tC">
                <span class="visGraphText">
                <?php
                echo $entities[$key]->getName()."<br/>";
                echo $attributes[$key][0]->GetName().": ".$attributes[$key][0]->GetValue();
                for ($j=1 ; $j < $numAttributes ; $j++)
                    echo ", ".$attributes[$key][$j]->GetName().": ".$attributes[$key][$j]->GetValue();
                ?>
                </span>
                </td>
                <td class="tC">
                <div id="pb<?php echo $i+1?>" style="width: 400px; height: 20px;"></div>
                <?php echo 'Score: '.number_format($rankArray[1][$key], 2, ".","").' <span class="matchText">(<span class="percText">'.number_format($normScores[$key], 1, ".", "").'%</span> match)</span>'; ?>
                </td>
            </tr>
            <?php
            $i++;
            }
            ?>
            </tbody>
        </table>
    </div>

    <div id="pagerGraph" class="pager">
    	<form>
    		<img src="images/first.png" class="first"/>
    		<img src="images/prev.png" class="prev"/>
    		<input type="text" class="pagedisplay"/>
    		<img src="images/next.png" class="next"/>
    		<img src="images/last.png" class="last"/>
    	</form>
    </div>

    <!----------------------->
    <!-- Data matrix table -->
    <!----------------------->

    <div id="visMatrix">
            <table id="visMatrixTable" class="tablesorter">
                <thead>
                <tr>
                <th class="tC tCC">Entity name</th>
                <?php
                for ($i=0 ; $i < $numAttributes ; $i++)
                {
                    echo "<th class=\"tC tCC\">".$attributes[0][$i]->GetName()."</th>";
                }
                ?>
                <th class="tC tCC">Entity score</th>
                </tr>
                </thead>
                <tbody>
                <?php
                for ($i=0 ; $i < $numEntities ; $i++)
                {
                    echo "<tr>";
                    echo "<td class=\"tC tCC\">".$entities[$i]->getName()."</td>";
                    for ($j=0 ; $j < $numAttributes ; $j++)
                        echo "<td class=\"tC tCC\">".$attributes[$i][$j]->GetValue()."</td>";
                    echo "<td class=\"tC tCC\">".number_format($rankArray[1][$i], 2, ".","")."</td>";
                    echo "</tr>";
                }
                ?>
                </tbody>
        </table>

        <div id="pagerMatrix" class="pager">
        	<form>
        		<img src="images/first.png" class="first"/>
        		<img src="images/prev.png" class="prev"/>
        		<input type="text" class="pagedisplay"/>
        		<img src="images/next.png" class="next"/>
        		<img src="images/last.png" class="last"/>
        	</form>
        </div>
    </div>
</div>

<script type="text/javascript" src="js/genericLib.js"></script>
<script type="text/javascript" src="js/libs/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/libs/jquery.tablesorter.pager.js"></script>

<script type="text/javascript">
    var colors = getColorArray();

	$(document).ready(
        function(){
            var i = 0;

    	    <?php
            echo 'var scores = new Array('.implode(',', $normScores).');';
            echo 'var numEntities = "'.$numEntities.'";';
            ?>

            var tokens = $(".percText").text().split("%");
            var perc = new Array();

            for (var i = 0 ; i < numEntities ; i++)
            {
                $( "#pb"+(i+1) ).progressbar({
                    value: scores[i],
                    create: function(event, ui){
                        var selector = "#pb"+(i+1)+" > div";
                        var value = this.getAttribute( "aria-valuenow" );
                        if (value < 25){
                            $(selector).css({ "background": "Red" });
                        } else if (value < 50){
                            $(selector).css({ "background": "Orange" });
                        } else if (value < 75){
                            $(selector).css({ "background": "Yellow" });
                        } else{
                            $(selector).css({ "background": "LightGreen" });
                        }
                    }
                });

                perc.push( Math.round(tokens[i]) );
            }

            i=0;

            $(".matchText").each(function()
            {
                var colorVal = perc[i];
                $(this).css("color", colors[colorVal]);
                i++;
            });

            $("#visGraphTable").tablesorter({
                headers: {
                0: { sorter: false },
                1: { sorter: false }
                }
            })
            .tablesorterPager({container: $("#pagerGraph")});

            $("#visMatrixTable")
            .tablesorter({
                sortList: [[<?php echo $numAttributes+1?>,1]]
            })
            .tablesorterPager({container: $("#pagerMatrix")});
        });
</script>

<?php
require_once ('include/footer.php');
?>